/**
 * Copyright (c) Jan 21, 2013 1:42:52 PM WKM and/or its affiliates. 
 * Use is subject to license terms.
 * All rights reserved.
 */
package org.extblog.wkm.web.util;

import java.util.Date;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.extblog.wkm.web.vo.MailFormView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;

/**
 * @author WKM 邮件发送器 MailSenderUtil.java history 1.WKM - Jan 21, 2013 - Create
 *         File
 */
@Controller
public class MailSenderUtil {

	/** 日志输出 * */
	protected Logger log = LoggerFactory.getLogger(getClass());
	
	/** spring mail sender * */
	private JavaMailSenderImpl mailSender = null;

	public JavaMailSenderImpl getMailSender() {
		return mailSender;
	}

	@Resource
	public void setMailSender(JavaMailSenderImpl mailSender) {
		this.mailSender = mailSender;
	}

	/**
	 * 发送邮件
	 * 
	 * @param mail
	 *            mail bean 信息
	 * @return
	 */
	public boolean sendFormMail(MailFormView mail) {
		MimeMessage mimeMessage = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,
				EncodingUtil.UTF_8);
		try {
			helper.setFrom(mail.getFrom());
			helper.setTo(mail.getTo());
			helper.setSentDate(new Date());
			helper.setSubject(mail.getSubject());
			helper.setText(mail.getContent());
			mailSender.send(mimeMessage);
		} catch (MessagingException e) {
			log.error("发送邮件失败:" + e.getMessage());
			return false;
		} catch (MailException e) {
			log.error("发送邮件失败:" + e.getMessage());
			return false;
		}
		log.info("向邮箱[" + mail.getTo() + "]发送邮件成功！");
		return true;
	}

	/**
	 * 发送邮件
	 * 
	 * @param mail
	 *            mail bean 信息
	 * @return
	 */
	public static boolean sendMail(MailFormView mail) {
		MailSenderUtil sender = ApplicationContextUtil.getApplicationContext().getBean(MailSenderUtil.class);
		return sender.sendFormMail(mail);
	}

}
